package com.originskyseed.platform.job.jobhandler.count;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Component;

import com.originskyseed.platform.core.job.biz.model.ReturnT;
import com.originskyseed.platform.core.job.handler.IJobHandler;
import com.originskyseed.platform.core.job.handler.annotation.JobHandler;
import com.originskyseed.platform.core.job.log.JobLogger;
import com.originskyseed.platform.count.service.IUserSalaryService;
import com.originskyseed.platform.user.service.IUserInfoService;

/**
 * 统计工资结算功能
 * 
 * @Author: twh @date: 2021/6/3
 */

@Component
@JobHandler(value = "userSalaryHandler")
public class UserSalaryHandler extends IJobHandler {

	@DubboReference
	private IUserInfoService userInfoService;

	@DubboReference
	private IUserSalaryService userSalaryService;

	@Override
	public ReturnT<String> execute(String tenantCode) throws Exception {
		try {
			// 获取开始统计的时间
			List<String> params = Arrays.asList(tenantCode.split(","));

			// 如果有传参则根据传递的参数查询，没有则根据当前日期查询
			String time = null;
			SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM");
			if (params.size() > 1) {
				time = params.get(1);
				tenantCode = params.get(0);
			} else {
				time = sim.format(new Date());
			}
			this.userSalaryService.insertsUserSalaryByTime(time, tenantCode);
		} catch (Exception e) {
			JobLogger.log("统计业务员工资数据：" + getExceptionDetail(e));
			return FAIL;
		}
		return SUCCESS;
	}

	/**
	 * 获取两个时间之间的所有年月份
	 * 
	 * @param begDate
	 * @param endDate
	 * @return
	 * @throws Exception
	 */
	/*
	 * public static List<String> getMonthBetweenTime(String begDate,String endDate) throws Exception{ List<String> monthList = new ArrayList<>();
	 * 
	 * SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");// 格式化为年月 Calendar min = Calendar.getInstance(); Calendar max = Calendar.getInstance();
	 * 
	 * min.setTime(sdf.parse(begDate)); min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);
	 * 
	 * max.setTime(sdf.parse(endDate)); max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);
	 * 
	 * Calendar curr = min; while (curr.before(max)) { monthList.add(sdf.format(curr.getTime())); curr.add(Calendar.MONTH, 1); } return monthList; }
	 */

	/**
	 * 获取异常详细信息，知道出了什么错，错在哪个类的第几行 .
	 *
	 * @param ex
	 * @return
	 */
	public static String getExceptionDetail(Exception ex) {
		String ret = null;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		PrintStream pout = new PrintStream(out);
		try {
			ex.printStackTrace(pout);
			ret = new String(out.toByteArray());
		} catch (Exception e) {
		} finally {
			try {
				pout.close();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return ret;
	}
}
